package com.lei.chinese_herbal_medicine.Controller;


import com.lei.chinese_herbal_medicine.Entity.PageData;
import com.lei.chinese_herbal_medicine.Entity.Result;
import com.lei.chinese_herbal_medicine.Entity.Token;
import com.lei.chinese_herbal_medicine.Entity.UserInfo;
import com.lei.chinese_herbal_medicine.Service.TokenService;
import com.lei.chinese_herbal_medicine.Service.UserInfoService;
import com.lei.chinese_herbal_medicine.Util.DateUtil;
import com.lei.chinese_herbal_medicine.Util.MenuUtil;
import com.lei.chinese_herbal_medicine.Util.UUIDUtil;
import org.apache.catalina.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (UserInfo)表控制层
 *
 * @author makejava
 * @since 2024-01-18 10:05:28
 */
@RestController
public class UserInfoController {
    /**
     * 服务对象
     */
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private TokenService tokenService;

    @PostMapping("/changeUserPermission")
    public Result changeUserPermission(UserInfo userInfo,HttpServletRequest request){
        Result result=new Result();
        Map map=new HashMap<>();
        result.setData(map);
        String tokenStr=request.getHeader("Authorization");
        Token token=new Token();
        token.setId(tokenStr);
        token=tokenService.getToken(token);
        if(token!=null){
            userInfo.setDateChanged(new Date());
            String nowPermission=token.getPermission();
            if(nowPermission==null||"".equals(nowPermission.trim())||"普通用户".equals(nowPermission.trim())){
                map.put("message","权限不足，授权失败！");
                result.setCode(403);
                return result;
            }
            boolean is=false;
            if("超级管理员".equals(nowPermission.trim())){
                is=userInfoService.updateUserInfo(userInfo);
            }else if("管理员".equals(nowPermission.trim())){
                String targePermission=userInfo.getPermission();
                if("普通用户".equals(targePermission.trim())||"管理员".equals(targePermission.trim())){
                    is=userInfoService.updateUserInfo(userInfo);
                }
            }
            if(is){
                map.put("message","授权成功！");
                result.setCode(200);
                return result;
            }
        }
        map.put("message","权限不足，授权失败！");
        result.setCode(403);
        return result;
    }
    @DeleteMapping("/deleteUser")
    public Result deleteUser(@RequestBody UserInfo userInfo,HttpServletRequest request){
        Result result=new Result();
        Map map=new HashMap<>();
        result.setData(map);
        String tokenStr=request.getHeader("Authorization");
        Token token=new Token();
        token.setId(tokenStr);
        token=tokenService.getToken(token);
        if(token!=null){
            String nowPermission=token.getPermission();
            if(nowPermission==null||"".equals(nowPermission.trim())||"普通用户".equals(nowPermission.trim())){
                map.put("message","权限不足，删除失败！");
                result.setCode(403);
                return result;
            }
            boolean is=false;
            if("超级管理员".equals(nowPermission.trim())){
                is=userInfoService.deleteUser(userInfo.getId());
            }else if("管理员".equals(nowPermission.trim())){
                UserInfo targetUser=userInfoService.getUserInfo(userInfo.getId());
                if("普通用户".equals(targetUser.getPermission().trim())||"管理员".equals(targetUser.getPermission().trim())){
                    is=userInfoService.deleteUser(userInfo.getId());
                }
            }
            if(is){
                map.put("message","删除成功！");
                result.setCode(200);
                return result;
            }
        }
        map.put("message","权限不足，删除失败！");
        result.setCode(403);
        return result;
    }
    @GetMapping("/getUserList")
    public Result getUserList(UserInfo userInfo, PageData pageData){
        Result result=new Result();
        Map map=new HashMap<>();
        List<UserInfo> userInfos=userInfoService.getUserList(userInfo,pageData);
        result.setCount(pageData.getCount());
        map.put("message","查询成功");
        result.setCode(200);
        result.setList(userInfos);
        result.setData(map);
        return result;
    }
    @GetMapping("/getUserInfo")
    public Result getUserInfo(HttpServletRequest request){
        Result result=new Result();
        String tokenStr=request.getHeader("Authorization");
        Token token=new Token();
        token.setId(tokenStr);
        token=tokenService.getToken(token);
        UserInfo info=userInfoService.getUserInfo(token.getUserId());
        Map map=new HashMap();
        if(info==null){
            map.put("message","用户信息查询失败");
            result.setCode(403);
        }else{
            info.setPassword(null);
            map.put("user",info);
            map.put("message","用户信息查询成功");
            result.setCode(200);
        }
        result.setData(map);
        return result;
    }
    @PostMapping("/updateUserInfo")
    public Result updateUserInfo(MultipartFile file,UserInfo userInfo, HttpServletRequest request){
        Result result=new Result();
        Map map=new HashMap();
        result.setData(map);
        String tokenStr=request.getHeader("Authorization");
        Token token=new Token();
        token.setId(tokenStr);
        token=tokenService.getToken(token);
        if(token==null){
            result.setCode(403);
            map.put("message","未登录，更新失败！");
        }
        userInfo.setId(token.getUserId());
        userInfo.setDateChanged(new Date());
        if(file!=null&&!file.isEmpty()){
            try {
                userInfo.setImg(file.getBytes());
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        System.out.println("即将修改"+userInfo);
        boolean is=userInfoService.updateUserInfo(userInfo);
        if(is){
            result.setCode(200);
            map.put("message","更新成功");
        }else{
            result.setCode(500);
            map.put("message","服务器内部错误，更新失败！");
        }
        return result;
    }
    @PostMapping("/register")
    public Result register(@RequestBody UserInfo userInfo){
        Result result=new Result();
        Map map=new HashMap();
        result.setData(map);
        userInfo.setId(UUIDUtil.fastSimpleUUID());
        userInfo.setDateCreated(new Date());
        userInfo.setPermission("普通用户");
        boolean is=userInfoService.register(userInfo);
        if(is){
            result.setCode(200);
            map.put("message","注册成功");
        }else{
            result.setCode(403);
            map.put("message","该用户名已存在，注册失败！");
        }
        return result;
    }
    //403	Forbidden	服务器理解请求客户端的请求，但是拒绝执行此请求
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request){
        Result result=new Result();
        Map map=new HashMap();
        UserInfo info = userInfoService.login(userInfo);
        if(info==null){
            result.setCode(403);
            map.put("message","密码错误");
        }else{
            String token=UUIDUtil.fastSimpleUUID();
            Token tokenObj=new Token();
            tokenObj.setId(token);
            tokenObj.setUserId(info.getId());
            tokenObj.setPermission(info.getPermission());
            tokenObj.setCreationTime(new Date());
            tokenObj.setExpirationTime(DateUtil.getLaterDate(60));
            tokenObj.setIpAddr(request.getRemoteAddr());
            tokenObj.setStatus("activate");
            boolean is=tokenService.addToken(tokenObj);
            if(is){
                UserInfo u=new UserInfo();
                u.setId(info.getId());
                u.setLastLoginTime(new Date());
                u.setLastLoginLocation(request.getRemoteAddr());
                userInfoService.updateUserInfo(u);
                MenuUtil menuUtil=new MenuUtil();
                result.setCode(200);
                map.put("token",token);
                map.put("permission",info.getPermission());
                map.put("menu",menuUtil.getMenu(info.getPermission()));
                map.put("message","登录成功");
            }else{
                result.setCode(500);
                map.put("message","登录失败，请联系管理员！");
            }
        }
        result.setData(map);
        return result;
    }
}

